import React, { Component } from 'react';
import { Form, message } from 'antd';
import StepContentBottom from './StepContentBottom';
import LoginWrapper from '@/components/LoginWrapper';
import { email as emailReg, phone as phoneReg } from '@/utils/regexp';
import { connect } from 'dva';

const { AccountFormItem } = LoginWrapper;

@connect(({ loading: { models: { resetPassword } } }) => ({
  loading: !!resetPassword,
}))
class StepFirst extends Component {
  setAccountError = (errorMsg, account) => {
    const {
      form: { setFields },
    } = this.props;
    setFields({
      account: {
        value: account,
        errors: [new Error(errorMsg)],
      },
    });
  };
  handleSubmit = e => {
    e.preventDefault();

    const {
      form: { validateFields },
      dispatch,
      setStep,
    } = this.props;
    validateFields((err, values) => {
      if (!err) {
        // 异步检查帐号是否存在
        // setAccount(values.account);
        // 先检查是邮箱还是手机，确定字段名与调用的action
        let fieldName;
        if (emailReg.test(values.account)) {
          fieldName = 'mail';
        }
        if (phoneReg.test(values.account)) {
          fieldName = 'mobile';
        }

        //
        dispatch({
          type: `resetPassword/checkBy${fieldName}`,
          payload: values.account,
        })
          .then(() => {
            // 查询成功，有这个用户，跳转到第二步
            dispatch({
              type: 'resetPassword/saveInformation',
              payload: {
                type: fieldName,
                account: values.account,
                code: '',
              },
            });
            setStep(1);
          })
          .catch(errMsg => {
            message.error(errMsg);
          });

        //setStep(1);
      }
    });
  };

  render() {
    const { form, loading } = this.props;

    return (
      <>
        <Form onSubmit={this.handleSubmit}>
          <AccountFormItem form={form} focus id="account" />
          <StepContentBottom loading={loading} />
        </Form>
      </>
    );
  }
}

export default Form.create()(StepFirst);
